package com.ifast.oupei.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ifast.oupei.domain.OddsDO;
import com.ifast.oupei.vo.MatchVO;
import com.ifast.oupei.vo.OddsTrack;
import com.ifast.oupei.vo.OddsVO;

/**
 * ”http://m.win007.com/info/fixture/“+赛季+“/”+联赛id+“_0_”+轮次+“.htm” 联赛
 * “http://m.win007.com/info/cupmatch/”+赛季+“/”+联赛id+“_0_”编码+“.htm” 杯赛
 * 
 * @author Administrator
 *
 */
public class HTMLParserUtil {
	/**
	 * 根据地址获取document index:传入参数值，判断是否连接过多
	 * 
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static Document getUrlList(String url) throws IOException {
		Connection conn = Jsoup.connect(url).header("charset", "GBK").header("X-UA-Compatible", "IE=edge,chrome=1")
				.header("apple-mobile-web-app-capable", "yes").header("renderer", "webkit")
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0");
		Document doc = null;
		doc = conn.timeout(100000).ignoreHttpErrors(true).ignoreContentType(true).post();
		return doc;
	}

	/**
	 * 根据path获取Elements
	 * 
	 * @param doc
	 * @param path
	 * @return
	 */
	public static Elements getStringByPath(Document doc, String path) {
		return doc.select(path);
	}

	/**
	 * 获取比分
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String getScore(Integer ticketsId) throws IOException {
		String url = "http://m.win007.com/Compensate/" + ticketsId + ".htm";
		Document doc = getUrlList(url);
		return doc.select("div[id='homeScore']").text() + "-" + doc.select("div[id='guestScore']").text();
	}

	/**
	 * 获取变赔信息
	 * 
	 * @param doc
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 * @throws Exception
	 */
	public static List<OddsTrack> getOddsTrack(Integer id, Integer companyId, String date)
			throws IOException, ParseException {
		Document doc = getUrlList(
				"https://live.aicai.com/xiyaou/odds!getOddsTrack.htm?betId=" + id + "&companyId=" + companyId);
		Long matchDate = new SimpleDateFormat("yyyyMMddHHmm").parse(date).getTime();
		JSONObject jsonObject = JSONObject.parseObject(doc.text());
		JSONObject matchObject = jsonObject.getJSONObject("result");
		JSONArray oddsArray = matchObject.getJSONArray("europDetailOddsVoList");
		List<OddsTrack> oddsTrackList = new ArrayList<OddsTrack>();
		if (oddsArray.size() > 0) {
			for (int i = 0; i < oddsArray.size(); i++) {
				OddsTrack oddsTrack = new OddsTrack();
				JSONObject odds = oddsArray.getJSONObject(i); // 遍历 jsonarray
				Long time = odds.getJSONObject("createTime").getLong("time");
				Date dateTime = new Date();
				dateTime.setTime(time);
				oddsTrack.setTime(new SimpleDateFormat("yyyy-MM-dd  HH:mm").format(dateTime));
				oddsTrack.setUpdateInfo(getUpdateInfo(matchDate, time));
				oddsTrack.setWinInfo(odds.getString("winOdds"));
				oddsTrack.setTieInfo(odds.getString("drowOdds"));
				oddsTrack.setLosInfo(odds.getString("loseOdds"));
				oddsTrackList.add(oddsTrack);
			}
		}
		return oddsTrackList;
	}

	public static String getUpdateInfo(Long matchDate, Long time) {
		// 获得两个时间的毫秒时间差异
		Long diff = matchDate - time;
		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		return day + "天" + hour + "小时" + min + "分钟";
	}

	/**
	 * 计算两个相差时间的天数
	 * 
	 * @param matchDate
	 * @param time
	 * @return
	 */
	public static long getDiffDay(Long matchDate, Long time) {
		// 获得两个时间的毫秒时间差异
		Long diff = matchDate - time;
		long nd = 1000 * 24 * 60 * 60;
		// 计算差多少天
		long day = diff / nd;
		return day;
	}

	/**
	 * 获取比赛列表信息
	 * 
	 * @param doc
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static List<MatchVO> getMatchList(String url, String leagueName, String season, String cupMatchDetail,
			int period) throws IOException {
		List<MatchVO> matchList = new ArrayList<MatchVO>();
		Document doc = getUrlList(url);
		JSONObject jsonObject = JSONObject.parseObject(doc.text());
		// String status = jsonObject.getString("status");
		JSONObject matchObject = jsonObject.getJSONObject("result");
		JSONArray matchArray = matchObject.getJSONArray("matchList");
		int start = 0;// 开始位置
		int end = matchArray.size() - 1;// 结束位置
		if (period > 0) { // 当存在周期的时候
			int turn = Integer.parseInt(cupMatchDetail);
			start = (turn - 1) * period;
			end = turn * period - 1;
		}
		for (int i = start; i < end + 1; i++) {
			JSONObject match = matchArray.getJSONObject(i);
			MatchVO matchVO = new MatchVO();
			matchVO.setTurn(match.getString("round"));// 设置轮次
			matchVO.setTicketsId(match.getInteger("betId"));// 设置比赛id
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				matchVO.setMatchDate(sdf.parse(match.getString("matchTimeStr")));
			} catch (Exception e) {
			} // 设置比赛日期
			matchVO.setGuestTeam(match.getString("awayTeamName"));// 设置客队
			matchVO.setHomeTeam(match.getString("hostTeamName"));// 设置主队
			matchVO.setGuestteamId(match.getInteger("awayTeamId"));// 设置客队id
			matchVO.setHometeamId(match.getInteger("hostTeamId"));// 设置主队id
			matchVO.setGuestteamRanking(match.getString("awayRank"));// 设置主队排名
			matchVO.setHometeamRanking(match.getString("hostRank"));// 设置客队排名
			if ("COMPLETE".equalsIgnoreCase(match.getString("status"))) {
				matchVO.setScore(match.getString("hostScore") + "-" + match.getString("awayScore"));// 设置比分
				matchVO.setResult(match.getInteger("matchResult"));// 设置结果
			}
			matchList.add(matchVO);
		}
		return matchList;
	}

	/**
	 * 获取比赛列表信息
	 * 
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	// public static List<MatchVO> getMatchList(String url, String leagueName,
	// String season, String cupMatchCode,
	// int period, String cupMatchDetail) throws Exception {
	// int index = 0;
	// List<MatchVO> matchList = new ArrayList<MatchVO>();
	// Document doc = getUrlList(url);
	// Document matchDoc = null;
	// Elements eles = new Elements();
	// if (period > 0) {
	// int turn = Integer.parseInt(cupMatchCode);
	// eles = new Elements(doc.select("tr[align][onclick]").subList((turn - 1) *
	// period, turn * period));// 截取轮次比赛
	// } else {
	// eles = doc.select("tr[align][onclick]");// 获取tickets_id
	// }
	// // 对elements进行清洗
	//
	// String turn = null;
	// try {
	// turn =
	// doc.select("select[id='selRound']").select("option[selected]").text().replace("第",
	// "").replace("轮",
	// "");// 获取轮次
	// } catch (Exception e) {
	// }
	// if (turn == null || "".equals(turn))
	// turn = cupMatchDetail;
	// if (turn == null || "".equals(turn))
	// turn = cupMatchCode;
	// for (Element element : eles) {
	// String turnName = null;
	// index = index + 1;
	// try {
	// turnName = turn +
	// element.parent().parent().previousElementSibling().text();
	// } catch (NullPointerException e) {
	// turnName = turn;
	// }
	// MatchVO matchVO = new MatchVO();
	// String ticketsId = element.attr("onclick").replace("ToAnaly(",
	// "").replace(" ,-1)", "").replace(" ,0)", "");// 联赛id
	// matchVO.setTicketsId(Integer.parseInt(ticketsId));// 联赛id
	// matchVO.setTurn(turnName);
	// matchDoc = getUrlList("http://m.win007.com/Analy/Analysis/" + ticketsId +
	// ".htm");
	// // String data =
	// // matchDoc.select("td[class='gray']").first().text().replace(" 完场","");
	// String data = matchDoc.select("div[class='row']").first().text();
	// data = data.substring(data.length() - 11);
	// matchVO.setMatchDate(getDate(data, season));// 设置比赛日期
	// matchVO.setScore(matchDoc.select("div[id='homeScore']").text() + "-"
	// + matchDoc.select("div[id='guestScore']").text());// 设置比分
	// matchVO.setResult(getResult(matchVO.getScore()));// 设置结果
	// String hostTeam = matchDoc.select("div[class='name']").first().text();
	// String guestTeam = matchDoc.select("div[class='name']").last().text();
	// matchVO.setHometeam(hostTeam);
	// matchVO.setGuestteam(guestTeam);
	// Elements eles1 =
	// matchDoc.select("table[class='mytable']").get(0).select("tr[align='center']").select("td");
	// Elements eles2 =
	// matchDoc.select("table[class='mytable']").get(1).select("tr[align='center']").select("td");
	// // 设置主队积分
	// //matchVO.setHometeamScore(Integer.parseInt(eles1.get(8).text()));
	// // 设置客队积分
	// //matchVO.setGuestteamScore(Integer.parseInt(eles2.get(8).text()));
	// // 设置主队排名
	// //matchVO.setHometeamRanking(Integer.parseInt(eles1.get(9).text()));
	// // 设置客队排名
	// //matchVO.setGuestteamRanking(Integer.parseInt(eles1.get(9).text()));
	// matchList.add(matchVO);
	// }
	// return matchList;
	// }

	public static Integer getResult(String score) {
		String[] arrays = null;
		if (score.contains("-"))
			arrays = score.split("-");
		if (arrays.length == 2) {
			if (Integer.parseInt(arrays[0]) > Integer.parseInt(arrays[1])) {
				return new Integer("3");
			} else if (Integer.parseInt(arrays[0]) == Integer.parseInt(arrays[1])) {
				return new Integer("1");
			} else {
				return new Integer("0");
			}
		} else {
			return null;
		}
	}

	/**
	 * 根据页面显示时间和赛季，获取date格式日期
	 * 
	 * @param data
	 * @param season
	 * @return
	 * @throws ParseException
	 */
	public static Date getDate(String data, String season) throws ParseException {
		Date date = new Date();
		DateFormat df = new SimpleDateFormat("yy-MM-dd hh:mm");
		if (season.contains("-")) {
			String[] seasons = season.split("-");
			int month = Integer.parseInt(data.substring(0, 2));
			if (month > 8) {
				date = df.parse(seasons[0] + "-" + data);
			} else {
				date = df.parse(seasons[1] + "-" + data);
			}
		} else {
			date = df.parse(season + "-" + data);
		}

		return date;
	}

	/**
	 * 根据公司id、比赛id获取赔率信息(bu包含近赔、间隔赔)
	 * 
	 * @param ticketsId
	 * @param companyId
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static List<OddsDO> getOddsList(Integer id, Integer ticketsId, List<Integer> companyArray)
			throws IOException {
		String url = "https://live.aicai.com/xiyaou/odds!getOuzhi.htm?betId=" + ticketsId + "&propId=0&start=0&size=50";
		Document doc = getUrlList(url);
		JSONObject jsonObject = JSONObject.parseObject(doc.text());
		JSONObject matchObject = jsonObject.getJSONObject("result");
		JSONArray matchArray = matchObject.getJSONArray("europOddsList");
		List<OddsDO> oddsList = new ArrayList<OddsDO>();
		if (matchArray.size() > 0) {
			for (int i = 0; i < matchArray.size(); i++) {
				OddsDO oddsDO = new OddsDO();
				JSONObject odds = matchArray.getJSONObject(i); // 遍历 jsonarray
				if (companyArray.contains(odds.getInteger("companyId"))) {// 公司里面有
					if (odds.getInteger("companyId") == 26)
						oddsList.add(getAllOddsList(id, ticketsId, 26));// 立博
					if (odds.getInteger("companyId") == 23)
						oddsList.add(getAllOddsList(id, ticketsId, 23));// 韦德
					if (odds.getInteger("companyId") == 24)
						oddsList.add(getAllOddsList(id, ticketsId, 24));// 365
					if (odds.getInteger("companyId") != 26 && odds.getInteger("companyId") != 23
							&& odds.getInteger("companyId") != 24) {
						oddsDO.setOddswin(getDoubleData(odds.getInteger("firstWinOdds")));// 胜赔
						oddsDO.setMatchId(id);// 比赛id
						oddsDO.setCompanyId(odds.getInteger("companyId"));// 公司id
						oddsDO.setOddstie(getDoubleData(odds.getInteger("firstDrowOdds")));// 平赔
						oddsDO.setOddslos(getDoubleData(odds.getInteger("firstLoseOdds")));// 负赔
						oddsDO.setLossration(getLossRation(odds.getInteger("firstWinOdds"),
								odds.getInteger("firstDrowOdds"), odds.getInteger("firstLoseOdds")));// 负赔
						long createTime = odds.getJSONObject("createTime").getLong("time");
						Date date = new Date();
						date.setTime(createTime);
						oddsDO.setOddsdate(date);// 设置比赛日期
						oddsList.add(oddsDO);
					}
				}
			}
		}
		return oddsList;
	}

	/**
	 * 根据公司id、比赛id获取赔率信息(包含近赔、间隔赔)
	 * 
	 * @param ticketsId
	 * @param companyId
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static OddsDO getAllOddsList(Integer id, Integer ticketsId, Integer companyId) throws IOException {
		OddsDO oddsDO = new OddsDO();
		String url = "https://live.aicai.com/xiyaou/odds!getOddsTrack.htm?betId=" + ticketsId + "&companyId="
				+ companyId;
		Document doc = getUrlList(url);
		JSONObject jsonObject = JSONObject.parseObject(doc.text());
		JSONObject europObject = jsonObject.getJSONObject("result");
		JSONArray europArray = europObject.getJSONArray("europDetailOddsVoList");
		if (europArray.size() > 0) {

			oddsDO.setMatchId(id);// 比赛id
			oddsDO.setCompanyId(companyId);// 公司id
			JSONObject firstodds = europArray.getJSONObject(0);
			double win = getDoubleData(firstodds.getInteger("winOdds"));
			double tie = getDoubleData(firstodds.getInteger("drowOdds"));
			double los = getDoubleData(firstodds.getInteger("loseOdds"));
			long createTime = firstodds.getJSONObject("createTime").getLong("time");
			Date date = new Date();
			date.setTime(createTime);// 设置比赛日期
			oddsDO.setOddsdate(date);// 设置比赛日期
			Integer day = Integer.parseInt(new SimpleDateFormat("dd").format(date));
			oddsDO.setOddswin(win);// 设置主胜
			oddsDO.setOddstie(tie);// 设置主胜
			oddsDO.setOddslos(los);// 设置主胜
			oddsDO.setLossration(getLossRation(win, tie, los));// 设置赔付率

			String odds1 = "";
			String odds2 = "";
			Date oddsDate1 = new Date();
			Date oddsDate2 = new Date();

			for (int i = 1; i < europArray.size(); i++) {
				JSONObject odds = europArray.getJSONObject(i); // 遍历
				long time = odds.getJSONObject("createTime").getLong("time");
				Date tempdate = new Date();
				tempdate.setTime(time);
				Integer day1 = Integer.parseInt(new SimpleDateFormat("dd").format(tempdate));
				if (day1 == day) {// 同一天时间，近赔
					odds1 = Double.toString(getDoubleData(odds.getInteger("winOdds"))) + "/"
							+ Double.toString(getDoubleData(odds.getInteger("drowOdds"))) + "/"
							+ Double.toString(getDoubleData(odds.getInteger("loseOdds")));
					oddsDate1 = tempdate;
				}
				if (getDiffDay(time, createTime) >= 3) {
					odds2 = Double.toString(getDoubleData(odds.getInteger("winOdds"))) + "/"
							+ Double.toString(getDoubleData(odds.getInteger("drowOdds"))) + "/"
							+ Double.toString(getDoubleData(odds.getInteger("loseOdds")));
					oddsDate2 = tempdate;
				}
				createTime = time;// 重新赋值
			}
			if(odds1.length()>13)odds1=odds1.replace(".00/", "/").replace(".00", "").replaceAll("0/", "/");
			if(odds1.length()>13)odds1=odds1.substring(0, odds1.length()-1);
			if(odds2.length()>13)odds2=odds2.replace(".00/", "/").replace(".00", "").replaceAll("0/", "/");
			if(odds2.length()>13)odds2=odds2.substring(0, odds2.length()-1);
			oddsDO.setOdds1(odds1);
			oddsDO.setOdds2(odds2);
			oddsDO.setOddsdate1(oddsDate1);
			oddsDO.setOddsdate2(oddsDate2);
		}
		return oddsDO;
	}

	/**
	 * 保留两位小数
	 * 
	 * @param a
	 * @return
	 */
	public static double getDoubleData(Integer a) {
		Integer b = 10000;
		double f1 = new BigDecimal((float) a / b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return f1;
	}

	/**
	 * 获取赔付率
	 * 
	 * @param win
	 * @param tie
	 * @param los
	 * @return
	 */
	public static String getLossRation(double win, double tie, double los) {
		double a = 1 / (1 / win + 1 / tie + 1 / los);
		double b = 100 * a;
		String c = Double.toString(new BigDecimal(b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
		return c;
	}

	/**
	 * 获取赔付率
	 * 
	 * @param win
	 * @param tie
	 * @param los
	 * @return
	 */
	public static String getLossRation(Integer win, Integer tie, Integer los) {
		double a = 1 / (1 / getDoubleData(win) + 1 / getDoubleData(tie) + 1 / getDoubleData(los));
		double b = 100 * a;
		String c = Double.toString(new BigDecimal(b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
		return c;
	}

	/**
	 * 根据公司id、比赛id获取赔率信息
	 * 
	 * @param ticketsId
	 * @param companyId
	 * @return
	 * @throws Exception
	 */
	public static OddsVO get007OddsList(Integer ticketsId, Integer companyId, int index, String season) {
		String url = "http://m.win007.com/CompensateDetail/" + companyId + "/" + ticketsId + ".htm";
		try {
			Document doc = getUrlList(url);
			OddsVO oddsVO = new OddsVO();
			Elements eles = doc.select("table[class='mytable3']").get(1).select("tr").last().select("td");
			if (eles == null || eles.size() < 1) {
				return oddsVO;
			}
			oddsVO.setOddswin(eles.get(0).text());
			oddsVO.setOddstie(eles.get(1).text());
			oddsVO.setOddslos(eles.get(2).text());
			oddsVO.setLossration(eles.get(3).text());
			String date = eles.get(5).text();
			oddsVO.setOddsdate(getDate(date, season));
			return oddsVO;
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * 根据公司id、比赛id获取赔率信息
	 * 
	 * @param ticketsId
	 * @param companyId
	 * @return
	 * @throws Exception
	 */
	public static OddsVO get360OddsList(Integer ticketsId, Integer companyId, int index, String season) {
		String url = "http://odds.cp.360.cn/jczqdata/eurochange/match/" + ticketsId + "/gcid/" + companyId;
		// "http://m.win007.com/CompensateDetail/"+companyId+"/"+ticketsId+".htm";
		try {
			Document doc = getUrlList(url);
			OddsVO oddsVO = new OddsVO();
			Elements eles = doc.select("table").get(0).select("tr").last().select("td");
			if (eles == null || eles.size() < 1) {
				return oddsVO;
			}
			oddsVO.setOddswin(eles.get(2).text());
			oddsVO.setOddstie(eles.get(3).text());
			oddsVO.setOddslos(eles.get(4).text());
			oddsVO.setLossration(eles.get(11).text());
			String date = eles.get(0).text();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			oddsVO.setOddsdate(format.parse(date));
			return oddsVO;
		} catch (Exception e) {
			System.out.println(e.toString());
			return null;
		}

	}

	/**
	 * 对img进行闭合处理
	 * 
	 * @param content
	 * @return
	 */
	public static String getImageCotent(String content) {
		String s[] = content.split("<img");
		for (int i = 1; i < s.length; i++) {
			if (s[i].indexOf(">") > 0) {
				s[i] = s[i].replaceFirst(">", "/>");
			}
		}
		String returnCotent = "";
		if (s[0].indexOf(">") < 0) {
			returnCotent = "<img";
		} else {
			returnCotent = s[0] + "<img";
		}
		for (int i = 1; i < s.length; i++) {
			returnCotent += s[i];
			if (i < s.length - 1)
				returnCotent += "<img";
		}

		return returnCotent;
	}

	public static void main(String[] args) throws Exception {
		// OddsVO oddsVO = get360OddsList(1424981, 115, 0, "");
		// System.out.println(oddsVO.getOddsdate());
		// List<MatchVO> list =
		// HTMLParserUtil.getMatchList("http://m.win007.com/info/fixture/2017-2018/31_0_3.htm","西甲","2017-2018","3",0,"");
		// for (MatchVO matchVO : list) {
		// System.out.println(matchVO.getTicketsId()+matchVO.getTurn());
		// System.out.println(matchVO.getMatchDate());
		// System.out.println(matchVO.getScore());
		// System.out.println(matchVO.getHometeamScore()+"<<<<<<<"+matchVO.getHometeamRanking());
		// }
		// OddsVO oddsVO = getOddsList(1424600, 115, 1, "2017-2018");
		// System.out.println(getResult("1-2"));
		List<Integer> list = new ArrayList<>();
		list.add(26);
		list.add(21);
		list.add(23);
		list.add(24);
		list.add(140);
		List<OddsDO> odds = getOddsList(1, 1424893, list);
		for (OddsDO oddsDO : odds) {
			System.out.println(oddsDO.getOdds1() + "<<<" + oddsDO.getOdds2());
		}
	}
}
